package com.way.fileexplorer.adapters;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.way.fileexplorer.R;
import com.way.fileexplorer.util.FileSort;
import com.way.fileexplorer.util.FileUtil;
import com.way.fileexplorer.util.Slog;

public abstract class FileAdapter extends BaseAdapter implements View.OnClickListener{
    
    public String TAG = "FileAdapter";
    protected List<File> mFileList;
    protected String mCurrentString;
    protected String mTopString;
    protected Context mContext;

    protected boolean mIsInit;
    private Set<String> mCheckedItems = new HashSet<String>();

    public FileAdapter(Context context) {
        super();
        mFileList = new ArrayList<File>();
        mIsInit = false;
        mContext = context;
    }

    public void setFileList(List<String> filePathList) {
        final int sortType;
        final SharedPreferences settings =  mContext.getSharedPreferences(
                FileSort.FILE_SORT_KEY, 0);
        sortType = settings.getInt(FileSort.FILE_SORT_KEY, FileSort.SORT_BY_NAME);
        if (filePathList != null) {
            mIsInit = true;
            for (String path : filePathList) {
                final SharedPreferences settings2 = PreferenceManager.getDefaultSharedPreferences(mContext);
                boolean display = settings2.getBoolean("display_hide_file", false);
                Log.i(TAG,"display hidden file = " + display);
                File file = new File(path);
                if(file.isHidden()){
                    Log.i(TAG,file + "is hidden");
                    if(display){
                        if(file.exists()){
                            Log.i(TAG,"show " + file);
                            mFileList.add(file);
                        }
                    }
                }else{
                    if(file.exists()){
                        Log.i(TAG,"show " + file);
                        mFileList.add(file);
                    }
                }
            }
            FileSort sort = new FileSort(sortType);
            sort.sort(mFileList);
        }
    }

    public static class ViewHolder {
        ImageView fileIcon;
        TextView fileName;
        TextView fileMessage;
        CheckBox selectCb;
    }

    @Override
    public int getCount() {
        return mFileList.size();
    }

    @Override
    public Object getItem(int position) {
        return mFileList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vHolder = null;
        if (convertView == null) {
            vHolder = new ViewHolder();
            convertView = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.detailed_filelist_item, null);
            vHolder.fileIcon = (ImageView) convertView
                    .findViewById(R.id.file_icon);
            vHolder.fileIcon.setOnClickListener(this);
            vHolder.fileName = (TextView) convertView
                    .findViewById(R.id.file_item_list_name);
            vHolder.fileMessage = (TextView) convertView
                    .findViewById(R.id.file_item_list_msg);
            vHolder.selectCb = (CheckBox) convertView
                    .findViewById(R.id.select_checkbox);
            convertView.setTag(R.id.action_paste_mode_cancel,vHolder);
        } else {
            vHolder = (ViewHolder) convertView.getTag(R.id.action_paste_mode_cancel);
        }

        if ((null != mFileList) && (position < mFileList.size())) {// bug 202395
        File file = mFileList.get(position);
        boolean isDirectory = file.isDirectory();
        vHolder.fileName.setText(file.getName());
        Resources res = parent.getResources();
        String timeStr = FileUtil.getDateStr(file.lastModified());
        if (isDirectory) {
            String[] list = file.list();
            vHolder.fileMessage.setText(res.getString(
                    R.string.file_list_flodermsg, timeStr, ((list == null) ? 0
                            : list.length)));
        } else {
            String sizeStr = FileUtil.getFitSize(file.length());
            vHolder.fileMessage.setText(res.getString(
                    R.string.file_list_filemsg, timeStr, sizeStr));
        }
        convertView.setTag(R.id.viewtag_filepath, file.getPath());
        }
        return convertView;
    }

    public static Drawable getApkIcon(Context context, String apkPath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(apkPath,
                PackageManager.GET_ACTIVITIES);
        if (info != null) {
            ApplicationInfo appInfo = info.applicationInfo;
            appInfo.sourceDir = apkPath;
            appInfo.publicSourceDir = apkPath;
            try {
                return appInfo.loadIcon(pm);
            } catch (OutOfMemoryError e) {
                // TODO catch to do what?
                Slog.e(e.getMessage());
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean isEmptyList() {
        return mFileList.isEmpty();
    }

    public String getCurrentString() {
        return mCurrentString;
    }

    public String getTopString() {
        return mTopString;
    }

    public void setCurrentString(String current) {
        // XXX: Allow null here. Won't throw exception.
        if (current == null) {
            return;
        }
        mCurrentString = current;
    }

    public void setTopString(String top) {
        // XXX: Allow null here. Won't throw exception.
        if (top == null) {
            return;
        }
        mTopString = top;
    }
    
    public boolean isChecked(int position) {
        return mCheckedItems.contains(getItem(position).toString());
    }

    public void setChecked(int position, boolean checked) {
        String file = getItem(position).toString();
        if (checked) {
            mCheckedItems.add(file);
        } else {
            mCheckedItems.remove(file);
        }
    }

    public boolean isEmptyFolder() {
        return mFileList.isEmpty();
    }

    public void checkAll(boolean checked) {
        if (checked) {
            int count = getCount();
            for (int i = 0; i < count; ++i) {
                String file = getItem(i).toString();
                mCheckedItems.add(file);
            }
        } else {
            mCheckedItems.clear();
        }
    }
    
    public boolean isAllChecked(){
        return mCheckedItems.size() == getCount()?true:false;
    }
    
    public List<File> getFileList(){
        return mFileList;
    }

    public void startSort() {
        if (null == mFileList || mFileList.isEmpty()) {
            return;
        }
        Slog.d("start sort");
        FileSort.getFileListSort().sort(mFileList);
        
    }

    @Override
    public void onClick(View view) {
    	if(view != null){
    		switch (view.getId()) {
            case R.id.file_icon:
            	if(view.getParent() != null){
            		view.showContextMenu();
            	}  	
                break;
            }
    	}
    }
}
